package com.bjc.listener;

import com.bjc.utils.JdbcUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @program: servlet
 * @description: 监听器优化查询性能
 *  因为没优化之前每次查询大量时间用在创建数据库的连接上  所以比较耗性能
 *  用监听器在servlet启动的时候创建几个数据库连接池 减少每次查询创建数据库连接
 * @author: bjc
 * @create: 2021-08-20 22:05
 */
public class OneListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        JdbcUtil jdbcUtil = new JdbcUtil();
        Map map = new HashMap();
        for (int i = 0; i < 5; i++) {
            Connection con = jdbcUtil.getCon();
            System.out.println("在Http服务器启动时，创建Connection");
            map.put(con,true);
        }
        //为了在Http服务器运行期间，一直都可以使用Connection，将Connection放到全局作用域对象中
        ServletContext context = servletContextEvent.getServletContext();
        context.setAttribute("key1",map);
    }

    /**
     * 在服务器关闭时销毁创建的Connection对象
     * @param servletContextEvent
     */
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        ServletContext context = servletContextEvent.getServletContext();
        Map map = (Map) context.getAttribute("key1");
        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()){
            Connection next = (Connection) iterator.next();
            if (next!=null){
                System.out.println("关闭，"+next);
                try {
                    next.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
